<template>
  <div class="cart">
    <!-- 没有购物车记录显示文字 -->
    <div class="no" v-if="cartList.length == 0">
      <img src="@/assets/img/nocart.jpeg" width="100%" />
      <h1 @click="$router.push('/home')">去购物</h1>
    </div>
    <div v-else>
      <van-checkbox-group v-model="result">
        <van-checkbox
          @click="selfCheck"
          :name="item"
          v-for="item in cartList"
          :key="item.id"
        >
          <van-swipe-cell>
            <van-card
              :num="item.number"
              :price="item.retail_price"
              :desc="item.goods_name"
              :title="item.goods_specifition_name_value"
              :thumb="item.list_pic_url"
            />
            <!-- 带滑动删除 -->
            <template #right>
              <van-button
                square
                text="删除"
                type="danger"
                class="delete-button"
                @click="deleteCart(item.product_id)"
              />
            </template>
          </van-swipe-cell>
        </van-checkbox>
      </van-checkbox-group>
      <!-- 提交订单 -->
      <van-submit-bar :price="allPrice" button-text="提交订单">
        <van-checkbox v-model="checked" @change="allCheck">全选</van-checkbox>
        <template #tip>
          你的收货地址不支持同城送, <span>修改地址</span>
        </template>
      </van-submit-bar>
    </div>
  </div>
</template>

<script>
import { getCartDate, deleteCart } from "@/utils/http.js";
export default {
  name: "Cart",
  data() {
    return {
      result: [], //复选框 存储选中数据
      cartList: [], //cart数据
      checked: false, //全选
    };
  },
  mounted() {
    // 获取数据
    getCartDate().then((res) => {
      this.cartList = res.data.cartList;
    });
  },
  computed: {
    allPrice() {
      let sum = 0;
      this.result.map((item) => {
        sum += item.retail_price * item.number;
      });
      return sum * 100;
    },
  },
  methods: {
    // 全选
    allCheck() {
      if (this.checked) this.result = this.cartList;
      else this.result = [];
    },
    // 单选
    selfCheck() {
      if (this.result.length == this.cartList.length) {
        this.checked = true;
      } else {
        this.checked = false;
      }
    },
    // 删除购物车
    deleteCart(id) {
      // 请求删除购物车
      deleteCart({ productIds: id + "" }).then((res) => {
        if (res.errno) {
          this.$toast("服务器出错啦");
        }
        this.$toast.success("删除成功啦");
        // 刷新
        this.$router.go(0);
      });
    },
  },
};
</script>

<style lang='less' scope>
.no {
  h1 {
    text-align: center;
    line-height: 100px;
    color: blue;
  }
  img {
    margin-top: 100px;
  }
}

.cart {
  padding-bottom: 150px;
}
.van-checkbox__label {
  flex: 1;
}
.van-submit-bar {
  bottom: 50px;
}
.goods-card {
  margin: 0;
  background-color: white;
}
.delete-button {
  height: 100%;
}
</style>